package com.hulk.dryad.manage.framework.websocket.server.cluster;

import cn.hutool.core.util.ObjectUtil;
import com.hulk.dryad.common.util.JacksonUtil;
import com.hulk.dryad.manage.framework.websocket.common.message.WsMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;


import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.lang.Nullable;

import java.nio.charset.StandardCharsets;

/**
 * websocket 集群的消息监听
 *
 * @author
 */
@Slf4j
@RequiredArgsConstructor
public class RedisWebSocketMessageListener implements MessageListener {
	private final ClusterWebSocketSender webSocketSender;

	@Override
	public void onMessage(Message message, @Nullable byte[] pattern) {
		byte[] channel = message.getChannel();
		if (log.isInfoEnabled()) {
			log.info("Redis sub onMessage channel:{}", new String(channel, StandardCharsets.UTF_8));
		}
		// 自行序列化，避免 redis 序列化问题
		byte[] messageBody = message.getBody();
		//WsMessage wsMessage = JacksonUtil.readValue(messageBody, WsMessage.class);
		WsMessage wsMessage = ObjectUtil.deserialize(messageBody);
		if (wsMessage != null) {
			webSocketSender.send(wsMessage);
		}
	}
}
